package com.kkang.betmachine.ryc;

import com.alibaba.fastjson.JSONObject;
import com.kkang.betmachine.config.MatheType;
import okhttp3.*;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author yongk_liu
 **/
public class ZuQiuRycNetUti {

    private static final String URL_DOMAIN = "http://59.110.9.126:8080/graphql-merger/graphql/12/1/1";

    public static List<ZuQiuRycMatche> pullMatch(MatheType matheType) {
        System.out.println("获取ZuQiuRyc比赛信息");
        List<ZuQiuRycMatche> list = null;
        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"query\":\"mutation GetJingcaiInfoMutation($input_0:getJingcaiInfoInput!) {getJingcaiInfo(input:$input_0) {clientMutationId,...F0}} fragment F0 on getJingcaiInfoPayload {getJingcaiInfo {result,leagues,error_code,message}}\",\"variables\":{\"input_0\":{\"argsInput\":{\"jingcaiValueType\":" + matheType.getJingcaiValueType() + ",\"imei\":11,\"jingcaiType\":" + matheType.getJingcaiType() + ",\"storeId\":\"ds51\"},\"clientMutationId\":\"4\"}}}");
        Request request = new Request.Builder()
                .url(URL_DOMAIN)
                .post(body)
                .addHeader("content-type", "application/json")
                .addHeader("cache-control", "no-cache")
                .addHeader("postman-token", "98552ef8-148c-ef0a-b5c3-acc718919605")
                .build();
        try {
            Response response = client.newCall(request).execute();
            ResponseBody body1 = response.body();
            String result = body1.string();
            list = hardMatcheParser(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 硬解析字符 比赛结果
     *
     * @param result
     * @return
     */
    private static List<ZuQiuRycMatche> hardMatcheParser(String result) {
        if (StringUtils.isEmpty(result))
            return null;
        int start = result.indexOf(":[[") + 3;
        int end = result.indexOf("]]}");
        if (start == end)
            return null;
        result = result.substring(start, end);
        result = result.replace("\\", "");
        result = result.replace("],[", ",");
        result = "[" + result + "]";
        return JSONObject.parseArray(result, ZuQiuRycMatche.class);
    }

}
